<?php
session_start(); //Starts sessions

if(isset($_SESSION['userNum']) && $_SESSION['voter_permission'] == 'Admin'){ //If the session variable is already set, get all session variables
	//Set all the session variables into local variables
	$userNum = $_SESSION['userNum'];
	$pageTitle = $_SESSION['title'];
	$server = $_SESSION['server'];
	$user = $_SESSION['user'];
	$pass = $_SESSION['pass'];
	$db = $_SESSION['db'];

	$ifLoginIsSingle = checkSessionID($_SESSION['sid'],$userNum,$server,$user,$pass,$db);//Check if session ID is as same as in the DB
			
			if($ifLoginIsSingle == "False"){
				session_destroy(); 
				header('Location: home.php');
			}

	$posIsCorrect = checkPosition($_GET['pos'],$_GET['name'],$server,$user,$pass,$db);//Check if the info in the GET method is valid

			if($posIsCorrect == "False"){//if it is not valid, redirect the user to the candEdit.php page
				header('Location: candEdit.php');
			}

}else{//If the user logged out, or usernum session is not existing

	header('Location: home.php');//else, redirect user to home

}

/*

FUNCTIONS OF CANDIDATE EDIT PAGE

1. Edit Candidate
   - Submit New Info function is to verify the editing
2. Add Candidate
3. Insert Candidate
4. Remove Candidate
   - Delete Candidate function is to verify the removal


*/

//EDIT CANDIDATE FUNCTION
if($_POST['editAction'] == "Edit Candidate"){

	$case = "case1";

//ADD CANDIDATE FUNCTION	
}else if($_POST['editAction'] == "Add Candidate"){

	$case = "case3";

//INSERT CANDIDATE FUNCTION
}else if($_POST['editAction'] == "Insert Candidate"){

	mysql_connect($server,$user,$pass) or die(mysql_error());
	mysql_select_db($db) or die(mysql_error());
	mysql_query("INSERT INTO candidates (Cand_Pos,Cand_Name,Cand_Party, Cand_Platform) VALUES ('".$_POST['candPos']."','".$_POST['candName']."','".$_POST['candParty']."','".$_POST['candPlatform']."')");
	$case = "case4";

//REMOVE CANDIDATE FUNCTION
}else if($_POST['editAction'] == "Remove Candidate"){

	$case = "case2";

//REMOVE CANDIDATE - Delete candidate function	
}else if($_POST['editAction']== "Delete Candidate"){

	mysql_connect($server,$user,$pass) or die(mysql_error());
	mysql_select_db($db) or die(mysql_error());
	mysql_query("delete from candidates where Cand_Num =".$_POST['candNum']."");
	
		//Deletes the image of the candidate to the candidate folder in the web server
        $myFile = "images/candidates/".$_POST['candNum'].".png";
		if(file_exists($myFile)){
		unlink($myFile);
		}
        	
	header("Location: candEdit.php?pos=".$_POST['curPosNum']."&name=".$_POST['curPosName']."");

//EDIT CANDIDATE - Submit new info function	
}else if($_POST['editAction'] == "Submit new Info"){

	mysql_connect($server,$user,$pass) or die(mysql_error());
	mysql_select_db($db) or die(mysql_error());
	mysql_query("UPDATE candidates SET Cand_Pos = '".$_POST['candPos']."', Cand_Name =  '".$_POST['candName']."', Cand_Party = '".$_POST['candParty']."', Cand_Platform = '".$_POST['candPlatform']."' WHERE Cand_Num = '".$_POST['candNum']."'");	
	$getPos = mysql_query("Select pos_name from positions where pos_num = ".$_POST['candPos']);
	$curPosName = "";
	
	while($getNewPos = mysql_fetch_array($getPos)){
		$curPosName = $getNewPos['pos_name'];//Gets the current position for display purposes at case5
	}
	
	$message = uploadImage($_POST['candNum']);//Uploads image
	$case = "case5";

}
?>
<html>
<head>
<title>Edit Candidates -<?php echo $pageTitle ?></title>
<?php include('showIcon.php'); ?>
</head>
<body style="background-image:url('images/bg_blue.jpg')">
<div style="position:absolute;left:75px;top: 0px">
<font face = "Arial">
<table style="width: 810px; height: 104px" border="0" cellspacing="0" cellpadding="0">
<?php include("menuButtons.php"); ?>
</table>
<table style="width: 810px;" cellspacing="0" cellpadding="0" class="style2">
<tr>
<td style="height: 76px; width: 28px;"></td>
<td style="height: 76px" width="808px">
<?php
/*
Check the case based from the steps taken above
case1 = Edit Function page
case2 = Verify deletion of candidate
case3 = Add Candidate page
case4 = Show confirmation of addition of candidate
case5 = Show confirmation of Editing of candidate
else = default page
*/
if($case == "case1"){

	echo "<h2><br>Edit ".$_POST['candName']."</h2>";
	echo "<br><form form name='newad' method='post' enctype='multipart/form-data'  action='candEdit.php'>";
	echo "<table style='height: 175px; width: 483px'><tr>";
	echo "<input type='hidden' name='curPosNum' value = '".$_POST['curPosNum']."'>";
	echo "<input type='hidden' name='curPosName' value = '".$_POST['curPosName']."'>";
	echo "<input type='hidden' name='candNum' value = '".$_POST['candNum']."'>";
	echo "<td style='width: 259px; height: 32px; background-color:silver'>Name: <input type='text' name='candName' value = '".$_POST['candName']."'></td>";
	
	$imgDest = "images/candidates/".$_POST['candNum'].".png"; //Checks if there is no picture in the candidate folder, uses nophoto image instead
	if(file_exists($imgDest)){
		echo "<td style='width: 212px;background-color:silver' rowspan='5' align='center' ><img src='images/candidates/".$_POST['candNum'].".png' width = '212' height = '248'><input type='file' name='image'></td></tr>";
	}else{
		echo "<td style='width: 212px;background-color:silver' rowspan='5' align='center' ><img src='images/nophoto.jpg' width = '212' height = '248'><input type='file' name='image'><br></td></tr>";
	}
	
	echo "<tr><td style='width: 259px; height: 41px; background-color:silver'>Party: <input type='text' name='candParty' value = '".$_POST['candParty']."'></td></tr>";
	echo "<tr><td style='width: 259px; height: 41px; background-color:silver'>Position:"; 
	
	//Gets all positions and put all info in the combobox
	mysql_connect($server,$user,$pass) or die(mysql_error());
	mysql_select_db($db) or die(mysql_error());
	
	$positions = mysql_query("Select * from positions where pos_close_vote = 1");
	
	echo "<select name='candPos'>";
		while($posLine = mysql_fetch_array($positions)){
		
		if($posLine['pos_num'] == $_POST['curPosNum']){
		echo "<option value='".$posLine['pos_num']."' selected='selected'>".$posLine['pos_name']."</option>";//Set selected the current Position
		}else{
		echo "<option value='".$posLine['pos_num']."'>".$posLine['pos_name']."</option>";
		}
		
		}
	echo "</select>";
	echo "</td></tr>";
	echo "<tr><td style='width: 259px; height: 41px; background-color:silver'>Description:</td></tr>";
	echo "<tr><td style='width: 259px; height: 130px'><font face='Times New Roman'><textarea name='candPlatform' style='height: 124px; width: 254px'>";
	echo $_POST['candPlatform']."</textarea></font></td></tr>";
	echo "<tr><td align='right' style='background-color:#CCCC99;height: 20px;border: 1px esolid #000000' colspan = '2'>";
	echo "<input style='background-color:lime' type='submit' name = 'editAction' value='Submit new Info'>";
	echo "</td></tr></table><br></form>";
	
	
}else if($case == "case2"){ 

	//Show the information of the candidate to be removed
	echo "<h2><br>Do you want to remove this candidate?</h2>";
	echo "<form action='candEdit.php' method='POST'>";
	echo "<table style='height: 175px; width: 483px'><tr>";
	echo "<input type='hidden' name='curPosNum' value = '".$_POST['curPosNum']."'>";
	echo "<input type='hidden' name='curPosName' value = '".$_POST['curPosName']."'>";
	echo "<input type='hidden' name='candNum' value = '".$_POST['candNum']."'>";
	echo "<td style='width: 259px; height: 32px; background-color:silver'>Name: <font color = 'white'>".$_POST['candName']."</font></td>";
	echo "<td style='width: 212px' rowspan='4' ><img src='images/candidates/".$_POST['candNum'].".png' width = '212' height = '248'></td></tr>";
	echo "<tr><td style='width: 259px; height: 41px; background-color:silver'>Party: <font color = 'white'>".$_POST['candParty']."</font></td></tr>";
	echo "<tr><td style='width: 259px; height: 41px; background-color:silver'>Description:</td></tr>";
	echo "<tr><td style='width: 259px; height: 130px'><font face='Times New Roman'><textarea readonly style='height: 124px; width: 254px'>";
	echo $_POST['candPlatform']."</textarea></font></td></tr>";
	echo "<tr><td align='right' style='background-color:#CCCC99;height: 20px;border: 1px esolid #000000' colspan = '2'>";
	echo "<input style='background-color:red' type='submit' name = 'editAction' value='Delete Candidate'>";
	echo "</td></tr></table><br></form>";
	
}else if($case == "case3"){
	
	//Prepares input for addition of candidate
	echo "<h2><br>Add Candidate</h2>";
	echo "<br><form action='candEdit.php' method='POST'>";
	echo "<table style='height: 175px; width: 483px'><tr>";
	echo "<td style='width: 259px; height: 32px; background-color:silver'>Name: <input type='text' name='candName' value = ''></td>";
	echo "<td style='width: 212px;background-color:silver' rowspan='5' ><img src='images/editPhoto.jpg' width = '212' height = '248'></td></tr>";
	echo "<tr><td style='width: 259px; height: 41px; background-color:silver'>Party: <input type='text' name='candParty' value = ''></td></tr>";
	echo "<tr><td style='width: 259px; height: 41px; background-color:silver'>Position:"; 
	
	//Get all positions and put it in combobox
	mysql_connect($server,$user,$pass) or die(mysql_error());
	mysql_select_db($db) or die(mysql_error());
	$positions = mysql_query("Select * from positions where pos_close_vote=1");
	
	echo "<select name='candPos'>";
		while($posLine = mysql_fetch_array($positions)){
		echo "<option value='".$posLine['pos_num']."'>".$posLine['pos_name']."</option>";
		}
	echo "</select>";
	echo "</td></tr>";
	echo "<tr><td style='width: 259px; height: 41px; background-color:silver'>Description:</td></tr>";
	echo "<tr><td style='width: 259px; height: 130px'><font face='Times New Roman'><textarea name='candPlatform' style='height: 124px; width: 254px'>";
	echo "</textarea></font></td></tr>";
	echo "<tr><td align='right' style='background-color:#CCCC99;height: 20px;border: 1px esolid #000000' colspan = '2'>";
	echo "<input style='background-color:blue' type='submit' name = 'editAction' value='Insert Candidate'>";
	echo "</td></tr></table><br></form>";
	
}else if($case == "case4"){

	echo "<br>Succesfully added candidate - <strong>".$_POST['candName']."</strong><br><br><a href='candEdit.php'>Go back to candidates</a>";

}else if($case == "case5"){
	
	echo "<br><strong>Edit Status - Successful</strong><br>";
	echo "<br><strong>Image upload status - ".$message."</strong><br><br>";
	echo "<a href='candEdit.php?pos=".$_POST['candPos']."&name=".$curPosName."'>Continue</a>";
	
}else{


// Using get method, use the information from hyperlink to show candidates
$num =$_GET['pos']; // The position chosen
$name = $_GET['name']; // The name of position
//The two are required to ensure that information shown is accurate

if(isset($_GET['pos'])){ //This means that the position chosen if from the database
						//The position number started at number 1
			  

echo "<br><h2>Candidates for ".$_GET['name']."</h2>";
//Connect to database			  
mysql_connect($server,$user,$pass) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());

// Get all candidates with the parameters chosen by tmhe user
$result = mysql_query("SELECT c.Cand_Num, c.Cand_Pos, c.Cand_Name, c.Cand_Party, c.Cand_Platform, p.pos_name FROM candidates c ,positions p WHERE c.Cand_Pos = p.pos_num and c.Cand_Pos =".$num." and p.pos_name ='".$name."' order by c.cand_num") or die(mysql_error());  
$hasResult = 'False';
// The output in html
while($row = mysql_fetch_array( $result )){ //Get all candidates, this will loop until all candidates are shown
	
	echo "<form action='candEdit.php' method='POST'>";
	echo "<table style='height: 175px; width: 483px'><tr>";
	echo "<input type='hidden' name='curPosNum' value = '".$num."'>";
	echo "<input type='hidden' name='curPosName' value = '".$name."'>";
	echo "<input type='hidden' name='candNum' value = '".$row['Cand_Num']."'>";
	echo "<input type='hidden' name='candName' value = '".$row['Cand_Name']."'>";
	echo "<input type='hidden' name='candParty' value = '".$row['Cand_Party']."'>";
	echo "<input type='hidden' name='candPlatform' value = '".$row['Cand_Platform']."'>";
	echo "<td style='width: 259px; height: 32px;background-color:#333333'>&nbsp; &nbsp;Name: <font color = 'silver'>".$row['Cand_Name']."</font></td>";
	$imgDest = "images/candidates/".$row['Cand_Num'].".png";
	
	if(file_exists($imgDest)){
		echo "<td style='width: 212px' rowspan='4' ><img src='images/candidates/".$row['Cand_Num'].".png' width = '212' height = '248'></td></tr>";
	}else{
		echo "<td style='width: 212px' rowspan='4' ><img src='images/nophoto.jpg' width = '212' height = '248'></td></tr>";
	}
	
	echo "<tr><td style='width: 259px; height: 41px;background-color:#6666FF'>&nbsp; &nbsp;Party: <font color = 'silver'>&nbsp;".$row['Cand_Party']."</font></td></tr>";
	echo "<tr><td style='width: 259px; height: 41px;background-color:#6666FF'>&nbsp; &nbsp;Description:</td></tr>";
	echo "<tr><td style='width: 259px; height: 130px'><textarea readonly style='height: 124px; width: 260px;background-color:#ccffFF;font-family:sans-serif'>";
	echo $row['Cand_Platform']."</textarea></td></tr>";
	echo "<tr><td align='right' style='background-color:#CCCC99;height: 20px;border: 1px solid #000000' colspan = '2'>";
	echo "<input type='image' name='editAction' value= 'Remove Candidate' src='images/remove.png' border='0' title='Remove ".$row['Cand_Name']." as candidate'/>";
	echo "<input type='image' name='editAction' value= 'Edit Candidate' src='images/add.png' border='0' title='Edit information about ".$row['Cand_Name']."'/>";
	echo "</td></tr></table><br></form>";
	$hasResult = 'True';
	
}
	
	echo "<form action='candEdit.php' method='POST'";
	echo "<table><tr><td><input style='background-color:#0066CC' type='submit' name = 'editAction' value='Add Candidate'></td></tr></table></form>";
	
	
}else{ // Means there are no parameters set yet, indicating the user needs to choose

//Connect to database
mysql_connect($server,$user,$pass) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());

//Get all the positions
$result = mysql_query("SELECT * FROM positions") or die(mysql_error());  

//HTML output
echo "<br><h2>Select a position</h2>";
while($row = mysql_fetch_array( $result ))
{
//Create hyperlinks to be used as a GET method
if($row['pos_close_vote'] == '1'){
echo "<a href = 'candEdit.php?pos=".$row['pos_num']."&name=".$row['pos_name']."' style='text-decoration:none'>".$row['pos_name']."</a><br>";
}else{
echo "".$row['pos_name']." - <font color=red size=1>Close voting to enable editing this position</font><br>";
}

}
}
}
//This function reads the extension of the file. It is used to determine if the file  is an image by checking the extension.
function getExtension($str) {
         $i = strrpos($str,".");
         if (!$i) { return ""; }
         $l = strlen($str) - $i;
         $ext = substr($str,$i+1,$l);
         return $ext;
}
function uploadImage($candNum){

	$errors=0;
	//checks if the form has been submitted
	 if(isset($_POST['editAction'])) 
	 {
	
	 define ("MAX_SIZE","100"); 
		//reads the name of the file the user submitted for uploading
		$image=$_FILES['image']['name'];
		//if it is not empty
		if ($image) 
		{
		
		//get the original name of the file from the clients machine
			$filename = stripslashes($_FILES['image']['name']);
		//get the extension of the file in a lower case format
			$extension = getExtension($filename);
			$extension = strtolower($extension);
		//if it is not a known extension, we will suppose it is an error and will not  upload the file,  
		//otherwise we will do more tests
	 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 
			{
			//print error message
				return "Unknown extension!";
				$errors=1;
			}
			else
			{
	//get the size of the image in bytes
	 //$_FILES['image']['tmp_name'] is the temporary filename of the file
	 //in which the uploaded file was stored on the server
	 $size=filesize($_FILES['image']['tmp_name']);

	//compare the size with the maxim size we defined and print error if bigger
	if ($size > MAX_SIZE*1024)
	{
		return "You have exceeded the size limit!";
		$errors=1;
	}

	//we will give an unique name, for example the time in unix time format
	$image_name=$candNum.'.png';
	//the new name will be containing the full path where will be stored (images folder)
	$newname="images/candidates/".$image_name;
	//we verify if the image has been uploaded, and print error instead
	$copied = copy($_FILES['image']['tmp_name'], $newname);
	if (!$copied) 
	{
		return "Upload not Successful";
		$errors=1;
	}}}}

	//If no errors registred, print the success message
	 if(isset($_POST['editAction']) && !$errors) 
	 {
		return "Upload Successfull";
		//continue - no mistake
	 }

}
//Function checkSessionID()
// -Checks if session in db is same in the session in browser
// If not, it logs out
function checkSessionID($sid,$uname,$sver,$usr,$passwd,$dbase){
mysql_connect($sver,$usr,$passwd) or die(mysql_error());
mysql_select_db($dbase) or die(mysql_error());

	$querySession = mysql_query("SELECT voter_current_session from voters WHERE voter_num = '".$uname."'");	

		while($sessionInDB = mysql_fetch_array($querySession)){
		$loggedSession = $sessionInDB['voter_current_session'];
		}

	if($_SESSION['sid'] == $loggedSession){
	return "True";
	}else{
	return "False";
	}	
}

function checkPosition($pos,$name,$sver,$usr,$passwd,$dbase){//Checks if position in the GET method is valid

mysql_connect($sver,$usr,$passwd) or die(mysql_error());
mysql_select_db($dbase) or die(mysql_error());

$checkPos = mysql_query("SELECT * from positions where pos_name = '".$name."' and pos_num = '".$pos."'and pos_close_vote = '1'");	
$ctr=0;

	while($position = mysql_fetch_array($checkPos)){
		$ctr = 1;
	}
	
	if($ctr == 0 && ($pos != "" || $name != "")){// If there is no result, or some info is not complete, return false
			return "False";
	}else{
			return "True";
	}
	
}
?>
</td>
</tr>
</table>
<br><br><br><br><br>
</div>
<?php include('bottomLinks.php'); ?>
</body>
</html>
	